<template>
  <section class='f-forget'>
    <van-sticky>
      <van-nav-bar class="f-nav-bar" title="忘记密码">
        <template #left>
          <van-icon name="arrow-left" size="18" @click="pageBack" />
        </template>
      </van-nav-bar>
    </van-sticky>

    <van-form ref="ruleFormRef" @submit="onSubmit" input-align="right" error-message-align="right">
      <van-cell-group>
        <van-field v-model="form.phone" clearable name="phone" label="手机号码" placeholder="请输入手机号码" type="tel" maxlength="11"
          :rules="[{ required: true, message: '请填写手机号码' },{ pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码'}]">
        </van-field>

        <van-field v-model="form.verificationCode" clearable name="verificationCode" label="验证码" placeholder="请输入验证码"
          type="number" maxlength="6" :rules="[{ required: true, message: '请填写验证码' }]">
          <template #button>
            <van-button size="small" type="warning" @click="getMsgCodeHandle">{{count? count + '秒': '获取验证码'}}</van-button>
          </template>
        </van-field>

        <van-field v-model="form.resetPassword" clearable name="resetPassword" label="新密码" placeholder="请输入新密码"
          :type="form.showResetPassword?'':'password'"
          :rules="[{ required: true, message: '请填写新密码' },{ validator: validatorPasswordNew, message: resetPasswordMsg }]">
          <template #right-icon>
            <van-icon v-show="!form.showResetPassword" name="closed-eye" @click="form.showResetPassword = true" />
            <van-icon v-show="form.showResetPassword" name="eye-o" @click="form.showResetPassword = false" />
          </template>
        </van-field>

        <van-field v-model="form.confirmPassword" clearable name="confirmPassword" label="确认密码" placeholder="请输入确认密码"
          :type="form.showConfirmPassword?'':'password'"
          :rules="[{ required: true, message: '请填写确认密码' },{ validator: validatorPasswordNew1, message: '两次密码不一致' }]">
          <template #right-icon>
            <van-icon v-show="!form.showConfirmPassword" name="closed-eye" @click="form.showConfirmPassword = true" />
            <van-icon v-show="form.showConfirmPassword" name="eye-o" @click="form.showConfirmPassword = false" />
          </template>
        </van-field>

      </van-cell-group>
      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import hexMD5 from "@/utils/md5.min.js"
import api from './api'
import { successDeal } from '@/utils/utils';
import { showDialog } from 'vant';

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref()

    const state = reactive({
      form: {
        phone: ''
      },

      counter: 0, // 计时器
      count: 0,
      passwordMsg: ''
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '重置密码',
        show: true,
        left: false,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });
    })

    const resetPasswordMsg = (value, rule) => {
      return state.passwordMsg
    }

    const validatorPasswordNew = (val) =>
      new Promise((resolve) => {
        const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (reg.test(val)) {
          resolve(true)
        } else {
          state.passwordMsg = '密码长度8位以上,由大写字母、小写字母、数字、特殊符号中三种方式组成'
          resolve(false)
        }
      });

    const validatorPasswordNew1 = (val) =>
      new Promise((resolve) => {
        if (state.form.resetPassword === val) {
          resolve(true)
        } else {
          resolve(false)
        }
      });


    // 获取短信验证码
    const getMsgCodeHandle = () => {
      if (state.count) return
      ruleFormRef.value.validate(['phone']).then(res => {
        state.count = 120;
        countDown();

        let json = {
          phone: state.form.phone,
          source: 1,
          type: 2, // 1-注册，2-找回密码 3-修改手机号
        }
        api.getMsgCode(json).then((res) => {
          console.log(res)
          if (res.code == 200) {
            successDeal('短信已发送！')
          }
        }).catch(err => {
          state.count = 0
          clearCounter()
        })
      })
    }

    //计时
    const countDown = () => {
      let count = state.count;

      clearCounter();
      state.counter = setInterval(() => {
        count--;
        state.count = count;
        if (count == 0) {
          clearCounter();
        }
      }, 1000);
    }

    //清除定时器
    const clearCounter = () => {
      clearInterval(state.counter);
    }

    const onSubmit = () => {
      let data = JSON.parse(JSON.stringify(state.form))
      let json = {
        "phone": data.phone,
        "resetPassword": hexMD5(data.resetPassword),
        "confirmPassword": hexMD5(data.confirmPassword),
        "source": 1,
        "verificationCode": data.verificationCode
      }
      api.submitResetPwd(json).then(res => {
        showDialog({
          title: '提示',
          message: '重置密码成功，请重新登录！',
        }).then(() => {
          router.go(-1)
        });
      })
    }

    const pageBack = () => {
      router.go(-1)
    };

    return {
      ...toRefs(state),
      ruleFormRef,
      getMsgCodeHandle,
      onSubmit,
      pageBack,
      resetPasswordMsg,
      validatorPasswordNew,
      validatorPasswordNew1
    }
  }
}
</script>
<style lang='scss' scoped>
.f-forget {
  .f-nav-bar {
    padding-top: 27px;
    background: #3273f4;
  }
  .f-submit-btn {
    margin-top: 70px;
    padding: 0 62px;
  }
}
</style>